package com.appheader.rongmaphone.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.appheader.rongmaphone.MainActivity;
import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.cache.preference.PreferenceUtil;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.utils.MD5;
import com.appheader.rongmaphone.utils.network.HttpUtil;
import com.yanzhenjie.permission.AndPermission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {


    private String baseURL = "";
    private EditText editName, editPassword;
    private TextView login;
    String strName, strPassword;
    private PreferenceUtil publicPreference;
    private PreferenceUtil userPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_login);
        initView();
        setListener();
        //动态申请权限
        AndPermission.with(this)
                .requestCode(101)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .send();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void setListener() {
        login.setOnClickListener(this);

    }

    private void initView() {
        baseURL = GlobalVars.getAppBaseUrl();
        editName = (EditText) findViewById(R.id.edit_name);
        editPassword = (EditText) findViewById(R.id.edit_password);
        login = (TextView) findViewById(R.id.login_btn);

    }

    private void AsyncPostOkHttp(String url, String name, String passWord) {

        HttpUtil.getLoginOkHttpClient(url, name, passWord, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", "onFailure: " + "-----------------------------");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String string = response.body().string();//返回json字符串获取sessionId，并存到缓存
                Log.e("LoginActicvity", "onResponse: " + string);
                //存到公共目录下
//   if (response.isSuccessful()) {
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    final String success = jsonObject.getString("success");
//                    Log.e("TAG", "onResponse: " + success);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success.equals("true")) {
                                publicPreference = new PreferenceUtil(getApplicationContext(),PreferenceUtil.PUB);
                                //存放到SharedPreferences中记录是第一次登录
                                publicPreference.putString("userStrs", string);
                                userPreference = new PreferenceUtil(getApplicationContext());
                                userPreference.putString("userStr",string);
                                userPreference.putBoolean("isFirst", true);

                                //能获取到
                                String userStr = publicPreference.getString("userStrs");
                                boolean login = userPreference.getBoolean("isFirst");
                                Log.e("TAG", "LoginActivity:------- " + login + "+++++" + userStr);
                                //存储个人信息到缓存中
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else if (success.equals("false")) {
//                            Log.e("TAG", "onResponse: " + "请求失败!");
                                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void loginMethod() {
        strName = editName.getText().toString().trim();
        strPassword = editPassword.getText().toString().trim();

        if (TextUtils.isEmpty(strName) || TextUtils.isEmpty(strPassword)) {
            Toast.makeText(LoginActivity.this, "用户名或者密码不能为空", Toast.LENGTH_SHORT).show();
        }
//        if (!isEmail(strName)) {
//            Toast.makeText(LoginActivity.this, "请输入正确邮箱账号", Toast.LENGTH_SHORT).show();
//        }
        String encrypt = MD5.encrypt(strPassword);
        AsyncPostOkHttp(GlobalVars.getAppBaseUrl(), strName, encrypt);

//        if (isEmail(strName)) {
//            }

        //MD5加密
//        AsyncPostOkHttp(GlobalVars.getAppBaseUrl(), strName, encrypt);
    }

    public static boolean isEmail(String email) {

        String t = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(t);
        Matcher m = p.matcher(email);
        return m.matches();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                loginMethod();//登录监听
                break;
        }
    }
}
